.SUFFIXES: 
.SUFFIXES: .o .cpp .h .d .l .y
.PHONY : doc clean

MAKE_INC := Makefile.inc
-include $(MAKE_INC)

MAKE_CFG := $(dir $(BASE_DIR)/)Makefile.cfg
ifneq "$(MAKECMDGOALS)" "clean"
  -include $(MAKE_CFG)
endif

CXX      := g++ #@CXX@
SED      := sed #@SED@
MV       := mv #@MV@
AR       := ar #@AR@
RM       := rm #@RM@
LN       := ln #@LN@
LEX      := flex #@FLEX@
YACC     := bison #@BISON@
DOXYGEN  := doxygen #@DOXYGEN@

ifeq ($(MAKE_TYPE), program)
	DEFINES += -DPROGRAM
endif

#ARFLAGS  := crus
ARFLAGS  := cru
CFLAGS	 := $(INCLUDES) $(DEFINES) $(C_OPT)
ifeq ($(MAKE_TYPE), program)
CFLAGS   += -DPROGRAM
endif
LFLAGS =
YFLAGS = -y

SRC      := $(wildcard *.c) $(wildcard *.cc) $(wildcard *.cpp)
ifdef NOT_SRC
  SRC := $(filter-out $(NOT_SRC),$(SRC))
endif
OBJECT   := $(foreach file, $(SRC), $(basename $(file)).o)

LEX_SRC  := $(wildcard *.l)
LEX_OBJ  := $(LEX_SRC:.l=.o)
OBJECT   := $(filter-out $(LEX_OBJ),$(OBJECT))
OBJECT   += $(LEX_OBJ)
YACC_SRC := $(wildcard *.y)
YACC_OBJ += $(YACC_SRC:.y=.o)
OBJECT   := $(filter-out $(YACC_OBJ),$(OBJECT))
OBJECT   += $(YACC_OBJ)

DEP_FILE := $(OBJECT:.o=.d)

SEARCH_SUBDIR = @for a in ${SUB_DIR}; do \
	             test -d "$$a" && \
                 test -f "$$a/${MAKE_INC}" && \
			   { echo "entering directory: $$a"; \
				 cd "$$a"; \
                 ${LN} -fs ../Makefile Makefile; \
        	     ${MAKE} $@; \
            	 ${RM} -f Makefile; \
				 echo "leaving directory: $$a"; \
                 cd ..; }; \
	             done

#	             done; exit 0

all: 
	${SEARCH_SUBDIR}; \
	if [ ! -z $(TARGET) ]; then ${MAKE} $(TARGET); fi

doc:
	cd $(DOC_DIR); \
	$(DOXYGEN) $(DOXY_CFG)

clean:
	-$(RM) -f $(TARGET) $(OBJECT) $(DEP_FILE) *~
#	@if [ -e $(MAKE_CFG) ]; then $(RM) $(MAKE_CFG); fi
	${SEARCH_SUBDIR}

ifneq "$(MAKECMDGOALS)" "clean"
  -include $(DEP_FILE)
endif

.c.o .cc.o .cpp.o: 
	$(CXX) $(CFLAGS) -c $<

.c.d .cc.d .cpp.d:
	$(CXX) $(CFLAGS) $(TARGET_ARCH) -M $< | \
	$(SED) 's,\($(notdir $*)\.o\) *:,$(dir $@)\1 $@: $(MAKE_INC) $(MAKE_CFG) ,' >$@.tmp
	$(MV) $@.tmp $@

.l.c .l.cc .l.cpp:
	$(LEX) $(LFLAGS) -+ -o$@ $<
	$(SED) 's/\<FlexLexer.h\>/\"parser\/FlexLexer.h\"/g' $@ >$@.tmp
	$(MV) $@.tmp $@

.y.c .y.cc .y.cpp:
	$(YACC) $(YFLAGS) -d $< -o $@

$(TARGET): $(OBJECT)
ifeq ($(MAKE_TYPE), library)
	$(AR) $(ARFLAGS) $@ $(OBJECT) $(LDADD)
	ranlib $@
else
	$(CXX) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJECT) $(LIBS)
endif
